/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package broadcast;

import BittorentPackage.BittorentPackageMessage;
import FolderChunks.FilenameChunk;
import UDP.Sender;
import common.function_common;
import common.global;
import java.io.*;
import java.net.*;
import java.util.*;
import java.text.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import managerPeer.Node;
import managerPeer.NodeMap;

public class BroadcastListener extends Thread {
    // Set a default listener port

    private int listenerPort = 59;
    private DatagramSocket listenerSocket = null;
    private static int MAX_PACKET_SIZE = 1000;

    // Default Constructor
    public BroadcastListener() {
        super();
        listenerPort = global.port;
        MAX_PACKET_SIZE = global.MAX_PACKET_SIZE;
    }

    // Alternate Constructor to Override Port
    public BroadcastListener(int newPort) {
        // overide port setting
        listenerPort = newPort;
    }

    @Override
    public void run() {
        byte[] buffer = new byte[MAX_PACKET_SIZE];
        // Create a packet to hold the data when it arrives

        DatagramPacket infoPacket =
                new DatagramPacket(buffer, MAX_PACKET_SIZE);
        try {
            listenerSocket = new DatagramSocket(this.listenerPort);
        } catch (Exception ex) {
            System.out.println(
                    "Problem creating socket on port: " + listenerPort);
            System.exit(-1);
        }

        // do an infinite loop
        while (true) {
            try {
                //System.out.println( "starting Bittorent Like …" );
                // Setting this value to 0 causes it to be an infinite timeout
                listenerSocket.setSoTimeout(0);
                listenerSocket.receive(infoPacket);

                // What address sent the packet
                InetAddress fromAddress = infoPacket.getAddress();
                if (global.sendMine) {
                    global.sendMine = false;
                    continue;
                }
                // Get the message within the packet
                byte[] msg = infoPacket.getData();
                int port = infoPacket.getPort();
                try {
                    BittorentPackageMessage pkReceived = function_common.deserializeBytes(msg);
                    switch (pkReceived.getM_Option()) {
                        case "1":
                            break;
                        case "2":// Peer send request fileName download
                            String fileName = (String) pkReceived.getM_Data();
                            if (!fileName.equals("")) {
                                String folderName = fileName;
                                ArrayList<String> myChunksKeeping = function_common.getListChunksOfFile(folderName, true, true);
                                if (!myChunksKeeping.isEmpty()) {
                                    String option = "2";
                                    Object data = new FilenameChunk(myChunksKeeping);
                                    BittorentPackageMessage pkSend = new BittorentPackageMessage(option, data);
                                    Sender send = new Sender();
                                    if (send != null) {
                                        send.sendData(port, fromAddress.getHostAddress(), pkSend);
                                    }
                                }
                            }
                            break;
                        case "3":
                            break;
                        case "4":
                            break;
                        default:
                            break;
                    }
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(BroadcastListener.class.getName()).log(Level.SEVERE, null, ex);
                }
            } catch (IOException ex) {
                // Print the exception and try to keep going
                ex.printStackTrace();
            }
        }
    }
}